package web.servlet.question;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.LyyBaseResponse;
import domain.Question;
import org.apache.commons.beanutils.BeanUtils;
import service.QuestionService;
import service.impl.QuestionServiceImpl;
import utils.LyyLogUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

@WebServlet("/addQuestion")
public class AddQuestionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        Map<String, String[]> parameterMap = request.getParameterMap();
        Question question=new Question();
        question.setProposeTime(new Date());
        Exception exception=null;
        try {
            BeanUtils.populate(question,parameterMap);
        } catch (Exception e) {
            exception=e;
            LyyLogUtil.logeE(e.getMessage());
        }
        QuestionService service=new QuestionServiceImpl();
        boolean b = false;
        try {
            b = service.addQuestion(question);
        } catch (Exception e) {
            LyyLogUtil.logeE(e.getMessage());
            exception=e;
        }

        LyyBaseResponse lyyBaseResponse=new LyyBaseResponse();
        if(exception!=null){
            lyyBaseResponse.setErrMsg(exception.getMessage());
            lyyBaseResponse.setStatus(0);
        }else {
            if(b){
                lyyBaseResponse.setStatus(1);
            }else {
                lyyBaseResponse.setStatus(0);
                lyyBaseResponse.setErrMsg("反馈失败！");
            }
        }
        ObjectMapper objectMapper=new ObjectMapper();
        objectMapper.writeValue(response.getOutputStream(),lyyBaseResponse);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
